<template>
  <el-form
    ref="loginForm"
    :rules="loginRules"
    :model="loginForm"
    class="login-form"
    status-icon
    label-width="0"
    v-if="
      (ddType == 'notInDingTalk' ||
        this.$store.getters.website.corpId == null) &&
      !larkType
    "
  >
    <h3 style="color: #1e9fff; text-align: center">系统登录</h3>
    <el-form-item prop="username">
      <el-input
        v-model="loginForm.username"
        size="small"
        auto-complete="off"
        placeholder="请输入用户名"
        @keyup.enter.native="handleLogin"
      >
        <i slot="prefix" class="icon-yonghuming" />
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        :type="passwordType"
        size="small"
        auto-complete="off"
        placeholder="请输入密码"
        @keyup.enter.native="handleLogin"
      >
        <i
          slot="suffix"
          class="el-icon-view el-input__icon"
          @click="showPassword"
        />
        <i slot="prefix" class="icon-mima"></i>
      </el-input>
    </el-form-item>
    <el-form-item v-if="website.validateCode" prop="code">
      <Verify
        ref="verify"
        :mode="'pop'"
        :captcha-type="'blockPuzzle'"
        :img-size="{ width: '330px', height: '155px' }"
        @success="verifySuccess"
      />
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        size="small"
        class="login-submit"
        @click.native.prevent="handleLogin"
        >登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapGetters } from "vuex";
import Verify from "@/components/verifition/Verify";
import request from "@/router/axios";
// 钉钉JSAPI
// 文档 https://www.npmjs.com/package/dingtalk-jsapi
// 安装 npm install dingtalk-jsapi

// 设置存储信息-文档 https://open.dingtalk.com/document/orgapp/set-storage-information
// 获取存储信息-文档 https://open.dingtalk.com/document/orgapp/obtain-storage-information
// 删除存储信息-文档 https://open.dingtalk.com/document/orgapp/delete-storage-information

import * as dd from "dingtalk-jsapi/entry/union"; // 如果你想要在此代码在PC端和移动端都执行，那你可以如此引入
import * as dingding from "dingtalk-jsapi"; // 如果你想要在此代码在PC端和移动端都执行，那你可以如此引入
import ddSetItem from "dingtalk-jsapi/api/util/domainStorage/setItem";
import ddGetItem from "dingtalk-jsapi/api/util/domainStorage/getItem";
export default {
  name: "Userlogin",
  components: {
    Verify,
  },
  data() {
    return {
      socialForm: {
        code: "",
        state: "",
      },
      loginForm: {
        username: "",
        password: "",
        code: "",
        randomStr: "blockPuzzle",
      },
      checked: false,
      code: {
        src: undefined,
        len: 4,
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          /* {
            pattern: /^([a-z\u4e00-\u9fa5\d]*?)$/, message: '请输入小写字母', trigger: 'blur'
          }*/
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度最少为6位", trigger: "blur" },
        ],
      },
      passwordType: "password",
      ddType: "notInDingTalk", //钉钉标识，判断是否是钉钉环境
      larkType: false, //飞书标识，用于判断是否是飞书环境
    };
  },
  computed: {
    ...mapGetters(["tagWel", "website"]),
  },
  mounted() {
    this.ddType = dd.env.platform;
    const params = this.$route.query;
    let corpId = null; //企业ID
    //此总方法是为了区分集团企业免登不是集团企业用户名密码登录并且防止登录超时回跳登录页后获取不到企业ID
    //是集团企业登录地址携带corpId参数，不是集团企业登录地址不携带，携带参数时将企业ID存储到全局变量，防止退出超时后跳转登录时没有corpId参数
    //不携带参数时直接获取全局企业ID变量
    if (!this.validatenull(params.corpId)) {
      //判断参数是否存在
      this.$store.getters.website.corpId = params.corpId; //放入全局变量
      corpId = this.$store.getters.website.corpId; //从全局变量取出
    } else {
      corpId = this.$store.getters.website.corpId; //从全局变量取出
    }
    // 只允许在钉钉内操作
    if (dd.env.platform != "notInDingTalk") {
      if (!this.validatenull(corpId)) {
        //获取授权码通过后台查询当前钉钉用户是否有已知账号
        this.getDingDingAuthCode(corpId);
      } else {
        //钉钉内默认填入上次登录成功的用户名密码
        var t = this;
        ddGetItem({
          name: "username",
          onSuccess: function (info) {
            t.loginForm.username = info.value;
          },
        });
        ddGetItem({
          name: "password",
          onSuccess: function (info) {
            t.loginForm.password = info.value;
          },
        });
      }
    }

    //飞书内执行
    if (window.h5sdk) {
      this.larkType = true; //设置当前为飞书环境 进行飞书免登
      //获取授权码通过后台查询当前飞书用户是否有已知账号
      this.getLarkAuthCode();
    }
  },
  methods: {
    showPassword() {
      this.passwordType === ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    handleLogin() {
      this.loginByUsername();
      // if (this.website.validateCode) {
      //   this.$refs.loginForm.validate((valid) => {
      //     if (valid) {
      //       this.$refs.verify.show()
      //     }
      //   })
      // } else {
      //   this.loginByUsername()
      // }
    },
    verifySuccess(params) {
      this.loginForm.code = params.captchaVerification;

      this.loginByUsername();
    },
    loginByUsername() {
      this.$store
        .dispatch("LoginByUsername", Object.assign({}, this.loginForm))
        .then(() => {
          console.log(1111111);
          // this.$router.push('/wel/index')

          // 钉钉内默认设置登录成功的用户名密码
          if (dd.env.platform != "notInDingTalk") {
            // 只允许在钉钉内操作
            ddSetItem({ name: "username", value: this.loginForm.username });
            ddSetItem({ name: "password", value: this.loginForm.password });
          }

          console.log(123, this.tagWel.value);
          this.$router.push({ path: this.tagWel.value }).catch((err) => {
            console.error("路由跳转失败:", err);
            console.log("当前tagWel.value:", this.tagWel.value);
          });
        });
    },
    //获取钉钉获取免登授权码。
    getDingDingAuthCode(corpId) {
      var t = this;
      dingding.runtime.permission.requestAuthCode({
        // corpId: "dinga50ef5c9a3ce5e19f5bf40eda33b7ba0", // 测试企业id
        corpId: corpId, // 正式企业id
        onSuccess: function (info) {
          t.checkDingDingBind(info.code, corpId); // 通过该免登授权码可以获取用户身份
        },
        onFail: function (err) {
          alert(JSON.stringify(err));
        },
      });
    },
    //钉钉内根据免登授权码进行查询用户信息，不存在则创建基础用户信息进行绑定并登录
    checkDingDingBind(code, corpId) {
      var t = this;
      let state = "DINGTALK";
      request({
        url: "/admin/social/ddBind",
        method: "post",
        params: { state, code },
      }).then((response) => {
        dingding.runtime.permission.requestAuthCode({
          // corpId: "dinga50ef5c9a3ce5e19f5bf40eda33b7ba0", // 测试企业id
          corpId: corpId, // 正式企业id
          onSuccess: function (info) {
            t.loginByCode(state, info.code); // 通过该免登授权码可以获取用户身份
          },
          onFail: function (err) {
            alert(JSON.stringify(err));
          },
        });
      });
    },
    //获取飞书免登授权码
    getLarkAuthCode() {
      var t = this;
      //依据App ID调用JSAPI tt.requestAuthCode 请求临时授权码code
      window.h5sdk.ready(() => {
        console.log("window.h5sdk.ready");
        window.tt.requestAuthCode({
          appId: "cli_a52a6c5c71f8100d",
          success: (info) => {
            const code = info.code;
            if (code.length <= 0) {
              t.error("飞书免登授权码为空。");
            } else {
              t.checkLarkBind(code);
            }
          },
          fail: (error) => {
            alert(JSON.stringify(error));
          },
        });
      });
    },
    //飞书内根据免登授权码进行查询用户信息，不存在则创建基础用户信息进行绑定并登录
    checkLarkBind(code) {
      var t = this;
      let state = "LARK";
      request({
        url: "/admin/social/larkBind",
        method: "post",
        params: { state, code },
      }).then((response) => {
        var t = this;
        //依据App ID调用JSAPI tt.requestAuthCode 请求临时授权码code
        window.h5sdk.ready(() => {
          window.tt.requestAuthCode({
            appId: "cli_a52a6c5c71f8100d",
            success: (info) => {
              const code = info.code;
              if (code.length <= 0) {
                t.error("飞书免登授权码为空。");
              } else {
                t.loginByCode(state, code);
              }
            },
            fail: (error) => {
              alert(JSON.stringify(error));
            },
          });
        });
      });
    },
    //免登授权码登录
    loginByCode(state, code) {
      var socialForm = {};
      socialForm.state = state;
      socialForm.code = code;
      this.$store.dispatch("LoginBySocial", socialForm).then(() => {
        this.$router.push({ path: this.tagWel.value });
      });
    },
  },
};
</script>

<style></style>
